package com.whjk.safework.task;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.db.nosql.redis.RedisDS;
import cn.hutool.json.JSONObject;
import com.mybatisflex.core.row.Db;
import com.mybatisflex.core.row.Row;
import com.whjk.safework.entity.ResponseData;
import com.whjk.safework.service.IWorkerService;
import com.whjk.safework.utils.LoaclDateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
public class CreatWorkerTask {

    @Autowired
    private IWorkerService workerService;

    //定时派发任务给员工
    /*	2025-06-01 01:01:01
        2025-06-02 01:01:01
        2025-06-03 01:01:01
        2025-06-04 01:01:01
        2025-06-05 01:01:01
        2025-06-06 01:01:01
        2025-06-07 01:01:01
        2025-06-08 01:01:01
    */
    @Scheduled(cron = "01 01 01 * * ?")
    private void addworkerToDolist(){

        String                  positionSql      = "select DISTINCT(t_worker.position_id) as id from t_worker";
        List<Row> positionRows     = Db.selectListBySql(positionSql);
        Map<Integer,List<Row>> orgSafeTargetMap = new HashMap<Integer,List<Row>>();

        for (Row r:positionRows) {
            Integer     position_id     =   r.getInt("id");
            String      orgSafeSql      =   "select * from t_org_safetarget where duty_id=?";
            List<Row>   orgSafeRows     =   Db.selectListBySql(orgSafeSql,position_id);
            orgSafeTargetMap.put(position_id,orgSafeRows);
        }
        String      sql     =   "select * from t_worker where work_status = ?";
        List<Row>   rows    =   Db.selectListBySql(sql,0);

        for (Row r:rows) {
            Integer     workerId     =  Integer.parseInt(r.get("id").toString());
            Integer     positionId   =  Integer.parseInt(r.get("position_id").toString());
            List<Row>   orgSafeRows  =  orgSafeTargetMap.get(positionId);
            List<Row>   in_row_list  =  new ArrayList<>();
            for(Row orgSafeR:orgSafeRows) {
                Row     insertRow = new Row();
                        insertRow.set("year",DateUtil.year(DateUtil.date()));
                        insertRow.set("worker_id",workerId);
                        insertRow.set("target_id",orgSafeR.get("org_target_id"));
                        insertRow.set("target_str",orgSafeR.get("org_target_str"));
                        insertRow.set("dutyinfo_id",orgSafeR.get("org_dutyinfo_id"));
                        insertRow.set("dutyinfo_str",orgSafeR.get("org_dutyinfo_str"));
                        insertRow.set("plan_id",orgSafeR.get("org_plan_id"));
                        insertRow.set("plan_str",orgSafeR.get("org_plan_str"));
                        insertRow.set("check_id",orgSafeR.get("org_check_id"));
                        insertRow.set("check_str",orgSafeR.get("org_check_str"));
                        insertRow.set("check_pc",orgSafeR.get("check_pc"));
                        insertRow.set("check_standard",orgSafeR.get("check_standard"));
                        insertRow.set("kind_id",orgSafeR.get("kind_id"));
                        insertRow.set("create_time", DateUtil.date());
                        insertRow.set("safetarget_id", orgSafeR.get("id"));

                if(orgSafeR.get("check_pc").equals("1次/每年")){
                    long yearnum  =  Db.selectCount("select count(*) from t_worker_target where  safetarget_id=? and worker_id=? and year=? and check_pc='1次/每年'",orgSafeR.get("id"),workerId,DateUtil.year(DateUtil.date()));
                    if(yearnum==0){
                        Row     yearRow  = LoaclDateUtil.getThisYearStartDay(1);
                                insertRow.set("start_time", yearRow.get("startDay"));
                                insertRow.set("end_time", yearRow.get("endDay"));
                        Db.insert("t_worker_target",insertRow);
                    }
                }
                if(orgSafeR.get("check_pc").equals("1次/每季度")){
                    Row  quarterRow  = LoaclDateUtil.getThisQuarterStartDay(1);
                    long quarternum  =  Db.selectCount("select count(*) from t_worker_target where  safetarget_id=? and worker_id=? and start_time=? and end_time =? and check_pc='1次/每季度' ",orgSafeR.get("id"),workerId,quarterRow.get("startDay"),quarterRow.get("endDay"));
                    if(quarternum==0){
                        insertRow.set("start_time", quarterRow.get("startDay"));
                        insertRow.set("end_time", quarterRow.get("endDay"));
                        Db.insert("t_worker_target",insertRow);
                    }
                }
                if(orgSafeR.get("check_pc").equals("1次/每月")){
                    Row  monthRow  = LoaclDateUtil.getThisMonthStartDay(1);
                    long monthnum  =  Db.selectCount("select count(*) from t_worker_target where  safetarget_id=? and worker_id=? and start_time=? and end_time =? and check_pc='1次/每月'",orgSafeR.get("id"),workerId,monthRow.get("startDay"),monthRow.get("endDay"));
                    if(monthnum==0){
                        insertRow.set("start_time", monthRow.get("startDay"));
                        insertRow.set("end_time", monthRow.get("endDay"));
                        Db.insert("t_worker_target",insertRow);
                    }
                }
                if(orgSafeR.get("check_pc").equals("1次/每周")){
                    Row  weekRow  = LoaclDateUtil.getThisWeekStartDay(1);
                    long weeknum  =  Db.selectCount("select count(*) from t_worker_target where  safetarget_id=? and worker_id=? and start_time=? and end_time =? and check_pc='1次/每周' ",orgSafeR.get("id"),workerId,weekRow.get("startDay"),weekRow.get("endDay"));
                    if(weeknum==0){
                        insertRow.set("start_time", weekRow.get("startDay"));
                        insertRow.set("end_time", weekRow.get("endDay"));
                        Db.insert("t_worker_target",insertRow);
                    }
                }
            }
            //  System.out.println(result.length);
        }
        System.out.println(DateUtil.date());
    }

    //定时推送小程序
   //@Scheduled(cron = "0/10 * * ? * *")   0 0 9 ? * 2

    /*
    * 	2025-05-31 09:00:00
        2025-06-01 09:00:00
        2025-06-02 09:00:00
        2025-06-03 09:00:00
        2025-06-04 09:00:00
        2025-06-05 09:00:00
        2025-06-06 09:00:00
        2025-06-07 09:00:00
    * */
    @Scheduled(cron = "0 0 9 ? * *")
    private void remindPush(){
        ResponseData responseData     =  new ResponseData();
        Jedis jedis            =  RedisDS.create().getJedis();
        String         token            =  jedis.get("access_token_min_program");
        if(token==null){
            token   =  cn.hutool.http.HttpUtil.get("https://api.lvz.zhaq.zgsepri.com/Index/refresh");

            if(token.equals("error")){
                responseData.setMsg("token fail");
            }
            else {
                List<Row> workerList   =   workerService.getPushWorker();

                for (Row workerRow:workerList) {
                    List<Row>  numRowList  =  Db.selectListBySql("select count(*) as num,check_pc from t_worker_target where   worker_id=? and pass_time  IS NULL  and   end_time<now() and DATE_FORMAT(start_time,'%Y')= ? group by check_pc",workerRow.getString("id"),DateUtil.year(DateUtil.date()));
                    int yq_week     =   0;
                    int yq_month    =   0;
                    int yq_quarter  =   0;
                    int yq_year     =   0;

                    for (Row numrow:numRowList) {
                        if(numrow.getString("check_pc").equals("1次/每周"))    yq_week       =   numrow.getInt("num");
                        if(numrow.getString("check_pc").equals("1次/每月"))    yq_month      =   numrow.getInt("num");
                        if(numrow.getString("check_pc").equals("1次/每季度"))  yq_quarter    =   numrow.getInt("num");
                        if(numrow.getString("check_pc").equals("1次/每年"))    yq_year       =   numrow.getInt("num");
                    }
                    JSONObject body    =   new JSONObject();
                    body.set("touser",workerRow.getString("open_id"));
                    body.set("template_id","jR_nsI0pIao2RCSU8FdVF2_JVxHxZA7I875bAXBZJSc");

                    String      thing5      =  "逾期"+(yq_week+yq_month+yq_quarter+yq_year)+"条";//,周"+yq_week+"条,月"+yq_month+"条,季度"+yq_quarter+"条
                    if(yq_week>0){
                        thing5 = thing5+"周"+yq_week+"条";
                    }
                    if(yq_month>0){
                        thing5 = thing5+"月"+yq_month+"条";
                    }
                    if(yq_quarter>0){
                        thing5 = thing5+"季度"+yq_quarter+"条";
                    }

                    JSONObject  json        =   new JSONObject();
                    json.set("thing1",new JSONObject().set("value","您的履职任务提醒"));
                    json.set("thing2",new JSONObject().set("value", "逾期任务自评提醒"));
                    json.set("time4",new JSONObject().set("value", DateUtil.now()));
                    json.set("thing5",new JSONObject().set("value",thing5));
                    body.set("data",json);
                    //发送
                    String accessToken  =  token;
                    String post         =  cn.hutool.http.HttpUtil.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + accessToken, body.toString());

                    Row  in_row = new Row();
                    in_row.set("open_id",workerRow.getString("open_id"));
                    in_row.set("day",DateUtil.year(DateUtil.date()));
                    in_row.set("msg",post);
                    in_row.set("create_time",DateUtil.date());
                    in_row.set("info",thing5);
                    workerService.addPushRecord(in_row);
                }
            }
        }
        else  System.out.println("not null:"+token);
    }


    @Scheduled(cron = "0 0 4 ? * *")
    private void doWorkerScore(){
      List<Row>  workerList   =  Db.selectListBySql("select * from t_worker   where work_status=0 and is_del=0 and user_id IS NOT NULL ");
      for (Row workerRow:workerList) {
          workerService.refreshWorkerScore(workerRow.getInt("id"), DateUtil.year(DateUtil.date()));
      }
    }


    @Scheduled(cron = "0 30 2 ? * *")
    private void doWorkerScoreMonth(){
     //   String   month =   DateUtil.format(DateUtil.date(),"yyyy-MM");
        List<String> monthList = new ArrayList<>();
        int currentYear = DateUtil.year(DateUtil.date()); // 获取当前年份
        int currentMonth = DateUtil.month(DateUtil.date()) + 1; // 当前月份（0~11，需+1）

        for (int i = 1; i <= currentMonth; i++) {
            String month = DateUtil.parse(currentYear + "-" + i, "yyyy-M").toString("yyyy-MM");
            List<Row>  workerList   =  Db.selectListBySql("select * from t_worker   where work_status=0 and is_del=0 and user_id IS NOT NULL ");
            for (Row workerRow:workerList) {
                workerService.refreshWorkersMonthSocre(workerRow.getInt("id"), month);    //refreshWorkerScore(workerRow.getInt("id"), DateUtil.year(DateUtil.date()));
            }
        }

    }



    //定时刷新部门积分
    @Scheduled(cron = "0 0 2 ? * *")
    private void doDeptScore(){
        String      startTime = LoaclDateUtil.getPreMonthFirstDay();
        String      endTime   = LoaclDateUtil.getCurrentMonthFirstDay();
        String      month     = LoaclDateUtil.getMonth(1,"yyyy-MM");
        List<Row>   orgList   =  Db.selectListBySql("select * from t_org where (level_idx=2 and is_have_child=0 and is_del=0) or (level_idx=3  and is_del=0)");

        for (Row orgRow:orgList) {
            String  worker_sql = "select t_worker.id,t_worker.name from t_worker join t_position on t_worker.position_id= t_position.id join t_org on t_position.dep_id=t_org.id "
                    +"where t_org.path like ? and  work_status=0 and t_worker.is_del=0 and t_worker.user_id IS NOT NULL";
            int workerTargetNum       =     0;
            int workerTargetNum_good  =     0;
            int workerTargetNum_ok    =     0;
            List<Row>  workerList     =     Db.selectListBySql(worker_sql, "%"+orgRow.get("path")+"%");

            for (Row worker:workerList) {
                // 查询任务数
                Row targetNum            =  Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=?", startTime, endTime, worker.getInt("id"));
                Row targetNum_good       =  Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=? and   my_check_result>=9",  startTime, endTime,  worker.getInt("id"));
                Row targetNum_ok         =  Db.selectOneBySql("select count(*) as num  from t_worker_target where  start_time>= ? and end_time<= ? and worker_id=? and my_check_time IS NOT NULL",  startTime, endTime,  worker.getInt("id"));
                int targetNum_num        =  targetNum.getInt("num");
                int targetNum_good_num   =  targetNum_good.getInt("num");
                int targetNum_ok_num     =  targetNum_ok.getInt("num");
                if(targetNum_num>0){
                    workerTargetNum         =   workerTargetNum+targetNum_num;
                    workerTargetNum_good    =   workerTargetNum_good+targetNum_good_num;
                    workerTargetNum_ok      =   workerTargetNum_ok+targetNum_ok_num;
                }
            }
            if (workerTargetNum>0){
                BigDecimal  targetNum_score      = new BigDecimal(workerTargetNum_good).divide(new BigDecimal(workerTargetNum),2,BigDecimal.ROUND_HALF_UP); // 优秀
                BigDecimal  targetNum_score_ok   = new BigDecimal(workerTargetNum_ok).divide(new BigDecimal(workerTargetNum),2,BigDecimal.ROUND_HALF_UP); // 完成
                String      path                 = orgRow.getString("path","");
                if(!path.equals("")){
                    String trimmedInput = path.replaceAll("^/|/$", "");
                    String[] parts = trimmedInput.split("/");

                    if (parts.length>=3) {
                        String  depId = parts[2];
                        long    count = Db.selectCount("select count(*) from t_dep_lz_num where dep_id=? and month=?",depId,month);
                        if(count==0){
                            Row row = new Row();
                                row.set("dep_id",depId);
                                row.set("org_id",parts[0]);
                                row.set("month",month);
                                row.set("worker_num",workerTargetNum); // 履职总数
                                row.set("finished_num",workerTargetNum_ok); // 完成总数
                                row.set("good_num",workerTargetNum_good); // 优秀总数
                                row.set("finished_pre",targetNum_score_ok);
                                row.set("ok_pre",targetNum_score);
                            Db.insert("t_dep_lz_num",row);
                        }
                        else if(count>0){
                            Row row_old = new Row();
                                row_old.set("dep_id",depId);
                                row_old.set("org_id",parts[0]);
                                row_old.set("month",month);
                            Row row = new Row();
                                row.set("dep_id",depId);
                                row.set("org_id",parts[0]);
                                row.set("month",month);
                                row.set("worker_num",workerTargetNum);
                                row.set("finished_num",workerTargetNum_ok);
                                row.set("good_num",workerTargetNum_good);
                                row.set("finished_pre",targetNum_score_ok);
                                row.set("ok_pre",targetNum_score);
                                row.set("update_time",DateUtil.now());
                            Db.updateByMap("t_dep_lz_num",row,row_old);
                        }
                    }
                }
                System.out.println("计算结果："+orgRow.get("name")+"_"+targetNum_score+"_"+targetNum_score_ok);
            }
        }
    }

}
